package cn.lyq.card.ui.achievement

import android.graphics.Color
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.Observer
import androidx.viewpager2.adapter.FragmentStateAdapter
import cn.lyq.card.R
import cn.lyq.card.base.BaseFg
import cn.lyq.card.data.model.AchievementInfo
import cn.lyq.card.data.src.Result
import cn.lyq.card.data.src.Status
import cn.lyq.card.utils.bindViewPager
import cn.lyq.card.utils.setSimpleData
import cn.lyq.card.utils.toMoney
import kotlinx.android.synthetic.main.fg_achievement.*
import kotlinx.android.synthetic.main.layout_tab_normal.*
import kotlinx.android.synthetic.main.layout_title.*


class AchievementFg : BaseFg() {

    private val mModel by lazy {
        getVMActivity(AchievementVM::class.java)
    }
    private val tabTitles = arrayOf("日业绩", "月业绩", "总业绩")
    private val mPageAdapter by lazy {
        PagerAdapter(requireActivity())
    }

    override fun getLayoutId(): Int {
        return R.layout.fg_achievement
    }

    override fun initView(view: View) {
        super.initView(view)
        layoutTitle.setBackgroundColor(Color.parseColor("#00000000"))
        imgBack.visibility = View.GONE
        viewPager.adapter = mPageAdapter
        tabLayout.setSimpleData(tabTitles)
        tabLayout.bindViewPager(viewPager)
    }

    override fun initObserver() {
        super.initObserver()
        mModel.dayInfo.observe(this, Observer {
            if (it?.status == Status.SUCCESS) {
                setData(it)
            }
        })
        mModel.monthInfo.observe(this, Observer {
            if (it?.status == Status.SUCCESS) {
                setData(it)
            }
        })
        mModel.allInfo.observe(this, Observer {
            if (it?.status == Status.SUCCESS) {
                setData(it)
            }
        })
    }

    private fun setData(it: Result<AchievementInfo>) {
        tvAmountMoney.text = it.data?.allVolume?.toMoney() ?: "0"
        tvAmountNum.text = "累计总笔数：${it.data?.allNumber ?: 0}"
    }

    private class PagerAdapter(fa: FragmentActivity) : FragmentStateAdapter(fa) {

        override fun getItemCount(): Int = 3

        override fun createFragment(position: Int): AchievementSubFg {
            return AchievementSubFg.newInstance(position)
        }

    }
}